<template>
  <div class="purchase-record-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>购买记录管理</span>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="用户名">
            <el-input
              v-model="searchForm.userName"
              placeholder="请输入用户名"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input
              v-model="searchForm.productName"
              placeholder="请输入商品名称"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="商品编号">
            <el-input
              v-model="searchForm.productCode"
              placeholder="请输入商品编号"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="店长名称" v-if="isAdmin">
            <el-input
              v-model="searchForm.storeManagerName"
              placeholder="请输入店长名称"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="状态" v-if="isAdmin">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option label="已完成" :value="1" />
              <el-option label="已取消" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="购买时间" v-if="isAdmin">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 购买记录列表 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        empty-text="暂无购买记录"
      >
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="nickname" label="用户昵称" width="120" />
        <el-table-column prop="storeManagerName" label="店长名称" width="120" v-if="isAdmin" />
        <el-table-column prop="productName" label="商品名称" min-width="120" />
        <el-table-column prop="productCode" label="商品编号" width="120" />
        <el-table-column prop="purchaseQuantity" label="购买数量" width="100" />
        <el-table-column prop="unitPrice" label="单价" width="100">
          <template #default="scope">
            ¥{{ scope.row.unitPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="总金额" width="120">
          <template #default="scope">
            ¥{{ scope.row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="purchaseStatus" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.purchaseStatus)">
              {{ getStatusText(scope.row.purchaseStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="购买时间" width="160">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="120" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="viewDetail(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="购买记录详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户名">{{ selectedRecord.username }}</el-descriptions-item>
        <el-descriptions-item label="用户昵称">{{ selectedRecord.nickname }}</el-descriptions-item>
        <el-descriptions-item label="店长名称" v-if="isAdmin">{{ selectedRecord.storeManagerName || '无' }}</el-descriptions-item>
        <el-descriptions-item label="商品名称">{{ selectedRecord.productName }}</el-descriptions-item>
        <el-descriptions-item label="商品编号">{{ selectedRecord.productCode }}</el-descriptions-item>
        <el-descriptions-item label="购买数量">{{ selectedRecord.purchaseQuantity }}</el-descriptions-item>
        <el-descriptions-item label="单价">¥{{ selectedRecord.unitPrice }}</el-descriptions-item>
        <el-descriptions-item label="总金额">¥{{ selectedRecord.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(selectedRecord.purchaseStatus)">
            {{ getStatusText(selectedRecord.purchaseStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="购买时间">{{ formatTime(selectedRecord.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatTime(selectedRecord.updateTime) }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ selectedRecord.remark || '无' }}</el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { adminPurchaseApi } from '@/api/adminPurchase'
import { getAllPurchasePage } from '@/api/purchase'
import { usePermissionStore } from '@/stores/permission'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const detailDialogVisible = ref(false)
const selectedRecord = ref({})

// 权限管理
const permissionStore = usePermissionStore()
const isAdmin = computed(() => permissionStore.hasPermission('admin:purchase:records:view'))

// 搜索表单
const searchForm = reactive({
  userName: '',
  productName: '',
  productCode: '',
  storeManagerName: '',
  status: null,
  dateRange: null
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 1:
      return 'success'
    case 2:
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 1:
      return '已完成'
    case 2:
      return '已取消'
    default:
      return '未知'
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

// 获取购买记录
const getTableData = async () => {
  loading.value = true
  try {
    let response
    
    if (isAdmin.value) {
      // 管理员使用详细的查询参数
      const params = {
        current: pagination.current,
        size: pagination.size,
        userName: searchForm.userName,
        productName: searchForm.productName,
        productCode: searchForm.productCode,
        storeManagerName: searchForm.storeManagerName,
        status: searchForm.status,
        startTime: searchForm.dateRange ? searchForm.dateRange[0] : null,
        endTime: searchForm.dateRange ? searchForm.dateRange[1] : null
      }
      response = await adminPurchaseApi.getRecordsPage(params)
    } else {
      // 店长等其他角色使用简化的查询参数
      const params = {
        page: pagination.current,
        size: pagination.size,
        keyword: searchForm.productName || searchForm.userName || ''
      }
      response = await getAllPurchasePage(params)
    }
    
    if (response.code === 200) {
      tableData.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取购买记录失败')
    }
  } catch (error) {
    console.error('获取购买记录失败:', error)
    ElMessage.error('获取购买记录失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getTableData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.userName = ''
  searchForm.productName = ''
  searchForm.productCode = ''
  if (isAdmin.value) {
    searchForm.storeManagerName = ''
    searchForm.status = null
    searchForm.dateRange = null
  }
  pagination.current = 1
  getTableData()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  getTableData()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  getTableData()
}

// 查看详情
const viewDetail = (record) => {
  selectedRecord.value = { ...record }
  detailDialogVisible.value = true
}

// 页面加载时获取数据
onMounted(() => {
  getTableData()
})
</script>

<style scoped>
.purchase-record-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
}

.search-area .el-form {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
}

.search-area .el-form-item {
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}
</style> 